package com.jiecao.news.jiecaonews.activity;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jiecao.news.jiecaonews.BaseActivity;
import com.jiecao.news.jiecaonews.R;
import com.jiecao.news.jiecaonews.backgroung.ShareTask;
import com.jiecao.news.jiecaonews.dao.NewsDao;
import com.jiecao.news.jiecaonews.util.DensityUtil;
import com.jiecao.news.jiecaonews.util.NetUtil;
import com.jiecao.news.jiecaonews.util.UtilsClass;
import com.jiecao.news.jiecaonews.util.cache.DownloadWebImgTask;
import com.jiecao.news.jiecaonews.util.cache.HtmlParser;
import com.jiecao.news.jiecaonews.util.cache.ImageGetFromHttp;
import com.jiecao.news.jiecaonews.util.constants.Constants;
import com.jiecao.news.jiecaonews.util.umeng.ShareUtils;
import com.jiecao.news.jiecaonews.util.view.LoaingBar;
import com.jiecao.news.jiecaonews.util.view.SlideIt;
import com.umeng.analytics.MobclickAgent;
import com.umeng.newxp.common.ExchangeConstants;
import com.umeng.newxp.controller.ExchangeDataService;
import com.umeng.newxp.view.ExchangeViewManager;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.UMSsoHandler;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.SinaSsoHandler;

/**
 * 新闻详情页
 * 
 * @author lidongwei
 * 
 */
public class NewsInfoActivity extends BaseActivity {
	private static final String TAG = "NewsInfoActivity";
	private RelativeLayout newsInfoHeadBack;// 头部返回
	private WebView newsInfoWebview;// webview
	private HtmlParser parser;// 解析新闻页
	private Long id;// 本文的id
	private int type;//文章展示的类型 1 为发表后展示，2为未发表就展示
	private String mfailingUrl;// 页面的地址
	private String infourl;
	private FrameLayout newsInfoContentFl;
	private ImageView showButton;
	private TextView newsDateWeatherHeadText;
	private TextView newsLunarHeadText;
	private ImageView shareSina;
	private ImageView shareTencent;
	private ImageView shareFriends;
	private ImageView info;
	private ImageView moreApp;
	
	private UMSocialService controller;
	private long lastClickTime = 0;
	private long dy;
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private String newsInfo = null;
	private NewsDao newsDao;
	private SlideIt slideIt;
	private LoaingBar lb;
	private String title;
	private String intro;
	private String icon;
	
	private UMImage mUMImgBitmap;
	
	//handler
//	Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_news_info);
		registerReceiver(finishbr, new IntentFilter(finish_br_name));
		newsInfoHeadBack = (RelativeLayout) findViewById(R.id.news_info_head_left_rl);
		newsDao = new NewsDao(this);
		showButton = (ImageView) findViewById(R.id.show_button);
		newsInfoContentFl = (FrameLayout) findViewById(R.id.news_info_content_fl);
		shareSina = (ImageView) findViewById(R.id.share_sina);
		shareTencent = (ImageView) findViewById(R.id.share_tencent);
		shareFriends = (ImageView)findViewById(R.id.share_friends);
		info = (ImageView) findViewById(R.id.info);
		moreApp = (ImageView)findViewById(R.id.back_banner_more_app);
		
		lb = new LoaingBar(this);
		dy = DensityUtil.dip2px(getApplicationContext(), 74);
		slideIt = new SlideIt(newsInfoContentFl);
		
		newsDateWeatherHeadText = (TextView)findViewById(R.id.news_date_weather_head_text);
		newsLunarHeadText  = (TextView)findViewById(R.id.news_lunar_head_text);
		newsDateWeatherHeadText.setText(UtilsClass.getNowDate());
		newsLunarHeadText.setText(UtilsClass.getLunar());
		
		//分享相关
		controller = UMServiceFactory.getUMSocialService(NewsInfoActivity.class.getName(),
				RequestType.SOCIAL);
		
		
		newsInfoHeadBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();

			}
		});

		Intent intent = getIntent();// 获得Intent
		id = intent.getLongExtra("id", -1);
		type = intent.getIntExtra("type", 1);
		intro = intent.getStringExtra("intro")==null?"":intent.getStringExtra("intro");
		title = intent.getStringExtra("title");
		icon = intent.getStringExtra("icon");
		
		mfailingUrl = Constants.ARTICLE_START + "?id=" + id;
		infourl = Constants.ARTICLE_START + "?id=" + id;
		mUMImgBitmap  = new UMImage(this,
				 BitmapFactory.decodeResource(getResources(),
				 R.drawable.share_pic));
		
		if(type==2){
			infourl = infourl+"&pre=true";
		}else{
			mUMImgBitmap = new UMImage(this, icon);

		}
		
		ShareUtils.initshare(NewsInfoActivity.this, mUMImgBitmap, infourl+"&down=true",  controller,title);
		
		shareSina.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				controller.setShareContent(title+infourl+"&down=true"+" #节操精选#");
//				 参数1为Context类型对象， 参数2为要分享到的目标平台， 参数3为分享操作的回调接口
				controller.postShare(NewsInfoActivity.this,SHARE_MEDIA.SINA, 
				        new SnsPostListener() {
				                @Override
				                public void onStart() {
//				                    Toast.makeText(NewsInfoActivity.this, "开始分享.", Toast.LENGTH_SHORT).show();
				                }

				                @Override
				                public void onComplete(SHARE_MEDIA platform, int eCode,SocializeEntity entity) {
				                     if (eCode == 200) {
//				                         Toast.makeText(NewsInfoActivity.this, "分享成功.", Toast.LENGTH_SHORT).show();
				                     } else {
				                          String eMsg = "";
				                          if (eCode == -101){
				                              eMsg = "没有授权";
				                          }
				                          Toast.makeText(NewsInfoActivity.this, "分享失败[" + eCode + "] " + 
				                                             eMsg,Toast.LENGTH_SHORT).show();
				                     }
				              }
				});
				new ShareTask(Constants.SHARE_FEED_BACK_URL,id,"android",Constants.SINA).execute();
			}
		});
		
		shareTencent.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				controller.setShareContent(title+intro);
				controller.directShare(NewsInfoActivity.this, SHARE_MEDIA.WEIXIN, null);
				new ShareTask(Constants.SHARE_FEED_BACK_URL,id,"android",Constants.WX).execute();
			}
			
		});
		
		shareFriends.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				controller.setShareContent(title+intro);
				controller.directShare(NewsInfoActivity.this, SHARE_MEDIA.WEIXIN_CIRCLE, null);
				new ShareTask(Constants.SHARE_FEED_BACK_URL,id,"android",Constants.WXCIRCLE).execute();
			}
		});
		
		info.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent();
				i.setClass(NewsInfoActivity.this, AboutActivity.class);
				startActivity(i);
			}
		});
		moreApp.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ExchangeDataService service = new ExchangeDataService();
				new ExchangeViewManager(NewsInfoActivity.this, service).addView(
						ExchangeConstants.type_list_curtain, null);

			}
		});
		
		

		newsInfoWebview = (WebView) findViewById(R.id.news_info_webview);
		initNewsInfoWebView();
		if(!NetUtil.isNetworkConnected(NewsInfoActivity.this)){
			Toast.makeText(NewsInfoActivity.this, "您的网络出现问题", Toast.LENGTH_SHORT).show();
		}
		loadNewsInfo();

		showButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (System.currentTimeMillis() - lastClickTime > 500) {
					slideIt.slideview(0, dy, 400, 0, showButton);
				}
				lastClickTime = System.currentTimeMillis();
			}
		});
	}

	private void initNewsInfoWebView() {
		newsInfoWebview.getSettings().setSupportZoom(false);
		newsInfoWebview.getSettings().setJavaScriptEnabled(true);
		newsInfoWebview.getSettings().setDomStorageEnabled(true);
		newsInfoWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);// 缓存模式,
		newsInfoWebview.getSettings().setLayoutAlgorithm(
				LayoutAlgorithm.SINGLE_COLUMN);// 内容单行显示
		newsInfoWebview.setWebViewClient(articleWebViewClient);
		newsInfoWebview.getSettings().setBlockNetworkImage(true);
		//适配不同密度问题
		int   screenDensity   = getResources().getDisplayMetrics(). densityDpi ;
		WebSettings.ZoomDensity   zoomDensity   = WebSettings.ZoomDensity. MEDIUM ;
		switch (screenDensity){
		case   DisplayMetrics.DENSITY_LOW :
		    zoomDensity = WebSettings.ZoomDensity.CLOSE;
		      break ;
		case   DisplayMetrics.DENSITY_MEDIUM :
		    zoomDensity = WebSettings.ZoomDensity.MEDIUM;
		      break ;
		case   DisplayMetrics.DENSITY_HIGH :
		    zoomDensity = WebSettings.ZoomDensity.FAR;
		      break ;
		}
		newsInfoWebview .getSettings().setDefaultZoom(zoomDensity) ;
//		newsInfoWebview.setBackgroundColor(0);
//		 int versionLevel = android.os.Build.VERSION.SDK_INT;
//		 if(versionLevel>10){//3.0以上关闭硬件加速，解决webview图片加载闪烁问题，但是有一定可能性造成oom
//			 newsInfoWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
//		 }
		
	}

	private final WebViewClient articleWebViewClient = new WebViewClient() {
		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			if (!failingUrl.startsWith("file")) {
				mfailingUrl = failingUrl;
				view.stopLoading();
				view.clearView();
				view.loadUrl("file:///android_asset/loading_error.html");
			}
		}

		// 在加载页面完毕后，加载网络图片
		public void onPageFinished(WebView view, String url) {
			// 如果不是加载本地html文件
			if (!url.startsWith("file")) {
				DownloadWebImgTask downloadTask = new DownloadWebImgTask(
						newsInfoWebview);
				List<String> urlStrs = parser.getImgUrls();
				String urlStrArray[] = new String[urlStrs.size() + 1];
				urlStrs.toArray(urlStrArray);
				downloadTask.execute(urlStrArray);
			}
			lb.dismiss();

		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			if (!url.startsWith("file")) {
			}
			super.onPageStarted(view, url, favicon);
		}

	};

	// 加载news info信息
	private void loadNewsInfo() {
		lb.show();
		newsInfo = newsDao.getNewsInfoById(id);
		newsInfoWebview.clearView();
		parser = new HtmlParser(newsInfoWebview, infourl, NewsInfoActivity.this, id,
				formatter.format(new Date()), newsInfo);
		parser.execute((Void) null);
	}

	private String getAidFromUrl(String url) {
		int start = url.indexOf("id=");// 获取位置
		String subStr = url.substring(start + 3);
		int end = subStr.indexOf("&");
		if (end != -1) {
			return subStr.substring(0, end);
		}
		return subStr;
	}
	
	@Override 
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    /**使用SSO授权必须添加如下代码 */
	    UMSsoHandler ssoHandler = controller.getConfig().getSsoHandler(requestCode) ;
	    if(ssoHandler != null){
	       ssoHandler.authorizeCallBack(requestCode, resultCode, data);
	    }
	}
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		}
	public void onPause() {
		lb.dismiss();
		super.onPause();
		MobclickAgent.onPause(this);
		}

}
